# -*- coding: utf-8 -*-
import scrapy
import random

from XCFScrapy.items import foodCategoryItem

class FoodscategoryspiderSpider(scrapy.Spider):
    name = 'foodsCategoryspider'
    allowed_domains = ['xiachufang.com']
    start_urls = ['http://www.xiachufang.com/explore/']

    def parse(self, response):

        foodscategorys = response.xpath("//div/ul[@class='plain list search-left-nav-list']/li")
        foodscategorys.pop(0)

        for category in foodscategorys:
            title = category.xpath("./a/text()").extract_first("")
            url = category.xpath("./a/attribute::href").extract_first("")
            categoryId = self.generate_code()
            if not url:
                title = "本周最受欢迎"
                url = "/explore/"

            item = foodCategoryItem()
            item['title'] = title
            item['url'] = "http://www.xiachufang.com"+url
            item['categoryId'] = categoryId

            yield item

    """
    随机生成4位数
    """
    def generate_code(self):
        # 定义一个空列表，每次循环，将拿到的值，加入列表
        random_num = []
        # choice函数：每次从seeds拿一个值，加入列表
        for i in range(4):
            random_num.append(str(random.randint(0, 9)))
        return "".join(random_num)